import React from 'react';
import { Form, Input, Icon, message } from 'antd';
import styles from '@/pages/WorkFlow/components/FormControls/index.less';

const OPTTEXT = '选项';
let itemKey;
const SelectOption = props => {
    const { value, onChange, prefix } = props;
    const dataArr = value.map((item, index) => ({ key: index + 1, ...item }));
    const generateKey = () => {
        if (!itemKey) itemKey = Math.max(...dataArr.map(item => item.key)) || 0;
        itemKey += 1;
        return itemKey;
    };

    // 添加新项
    const newOptionValue = key => {
        let obj = { label: OPTTEXT, value: OPTTEXT, key };
        if (dataArr.length > 0) {
            const arr = [];
            dataArr.forEach(item => {
                const temp = item.value.split(OPTTEXT);
                if (temp.length > 0) {
                    arr.push(Number(temp[1]) || 1);
                }
            });
            const max = Math.max(...arr);
            for (let i = 1; i <= max; i += 1) {
                // 判断数字是否在数组里面
                if (!arr.includes(i)) {
                    obj = { label: `${OPTTEXT}${i}`, value: `${OPTTEXT}${i}`, key };
                    break;
                } else if (i === arr.length) {
                    obj = { label: `${OPTTEXT}${i + 1}`, value: `${OPTTEXT}${i + 1}`, key };
                }
            }
        }
        return obj;
    };

    return dataArr.map((i, index) => (
        // eslint-disable-next-line react/no-array-index-key
        <div className={styles.selectList} key={`${prefix}-${i.key}`}>
            <Input
                onChange={e => {
                    const newsOption = {
                        label: e.target.value,
                        value: e.target.value
                    };
                    onChange(
                        dataArr.map(item => {
                            if (item.key === i.key) {
                                return { ...item, ...newsOption };
                            }
                            return item;
                        })
                    );
                }}
                placeholder="请输入"
                value={value[index].value}
                maxLength={50}
            />
            <div className={styles.icons}>
                <Icon
                    type="minus-circle"
                    onClick={() => {
                        if (dataArr.length < 2) {
                            message.error('至少一个选项');
                            return;
                        }
                        onChange(dataArr.filter(item => item.key !== i.key));
                    }}
                />
                <Icon
                    type="plus-circle"
                    onClick={() => {
                        onChange([...dataArr, newOptionValue(generateKey())]);
                    }}
                />
            </div>
        </div>
    ));
};
export default Form.create()(SelectOption);
